<?php


namespace app\api\controller\v1;


use app\api\model\User as UserModel;
use app\api\model\UserAddress;
use app\api\service\Token as TokenService;
use app\exception\SuccessMessage;
use app\exception\UserException;
use app\validate\api\AddressNew;
use think\Exception;

class Address
{
    /**
     *
     * @return mixed
     * @throws Exception
     *
     */
    public function createOrUpdateAddress()
    {

        $validate = new AddressNew();
        $validate->goCheck();
        // 根据token 获取用户 uid
        // 根据 UID 来查找用户数据， 判断用户是否存在，如果不存在，抛出异常
        //  获取用户从客户端提交来的地址信息
        // 根据用户地址信息是否存在，从而判断是添加地址还是更新地址
        $uid = TokenService::getCurrentID();
        $user = UserModel::getByUID($uid);
        if(!$user){
            throw new UserException();
        }
        $dataArray = $validate->getDataByRule(input('post.'));
        $userAddress = $user->address;
        if(!$userAddress){
//            $user->address()->save($dataArray);
            UserAddress::create($dataArray);
        }else{
            // 用这种方法 才能自动写入时间戳
            UserAddress::update($dataArray,['user_id'=>$uid]);
           // $user->address->save($dataArray);
        }
        return json(new SuccessMessage(),201);

    }
}